package com.why.config.security;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;


    @Autowired
    private DingTalkAuthenticationProvider dingTalkAuthenticationProvider;

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 安全配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //1.自定义钉钉登录过滤器
        DingTalkAuthenticationFilter dingTalkAuthenticationFilter = new DingTalkAuthenticationFilter(new ProviderManager(dingTalkAuthenticationProvider));
        dingTalkAuthenticationFilter.setAuthenticationFailureHandler((request, response, ex) -> {
            this.writeResponse(response, ex.getMessage());
        });
        dingTalkAuthenticationFilter.setAuthenticationSuccessHandler((request, response, ex) -> {
            this.writeResponse(response, "登录成功:用户为:" + JSONUtil.toJsonStr(SecurityContextHolder.getContext().getAuthentication().getPrincipal()));
        });

        //2.自定义账户密码登录过滤器
        CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(new ProviderManager(customAuthenticationProvider));
        customAuthenticationFilter.setAuthenticationFailureHandler((request, response, ex) -> {
            this.writeResponse(response, ex.getMessage());
        });
        customAuthenticationFilter.setAuthenticationSuccessHandler((request, response, ex) -> {
            this.writeResponse(response, "登录成功:用户为:" + JSONUtil.toJsonStr(SecurityContextHolder.getContext().getAuthentication().getPrincipal()));
        });

        //3.表单登录过滤器
        FormLoginAuthenticationFilter formLoginAuthenticationFilter = new FormLoginAuthenticationFilter(authenticationManager());


        // 跨域共享
        http.cors()
                .and()
                // 跨域伪造请求限制无效
                .csrf().disable()
                .authorizeRequests(expressionInterceptUrlRegistry -> {
                    expressionInterceptUrlRegistry
                            //通过钉钉登录接口
                            .antMatchers(HttpMethod.POST, "/ding-login").permitAll()
                            .antMatchers(HttpMethod.POST, "/custom-login").permitAll()
                            .anyRequest().authenticated();
                })
                .addFilterAt(dingTalkAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAt(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAt(formLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                //禁止默认表单登录
//                .formLogin().disable()
//                .authorizeRequests()
                // 访问/data需要ADMIN角色
//                .antMatchers("/user/aaa").hasRole("ADMIN")
                // 其余资源任何人都可访问
//                .anyRequest().permitAll()
//                .and()
                .sessionManagement()
                // 设置Session的创建策略为：Spring Security永不创建HttpSession 不使用HttpSession来获取SecurityContext
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 异常处理
                .exceptionHandling()
                // 匿名用户访问无权限资源时的异常
                .authenticationEntryPoint(new JWTAuthenticationEntryPoint());
    }


    private void writeResponse(HttpServletResponse response, String msg) {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.write(msg);
        out.flush();
        out.close();
    }


    /**
     * 跨域配置
     *
     * @return 基于URL的跨域配置信息
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        // CORS 配置对所有接口都有效
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
